package com.qf.openapi.zuul.filter;

import cn.hutool.crypto.digest.DigestUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

@Component
@Slf4j
public class SignFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 20;
    }

    @Override
    public boolean shouldFilter() {
        // 尊重前面过滤器的判断结果
        RequestContext currentContext = RequestContext.getCurrentContext();
        boolean b = currentContext.sendZuulResponse();

        return b;
    }

    @Override
    public Object run() throws ZuulException {

        //1. 重新计算签名
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();

        Map<String, String[]> parameterMap = request.getParameterMap();
        // 获取所有参数名的集合
        Set<String> paramNameSet = parameterMap.keySet();
        // 注意：去掉请求中的sign参数 !!!
        paramNameSet.remove("sign");
        // 排序参数
        ArrayList<String> paramList = new ArrayList<>(paramNameSet);
        paramList.sort(String::compareTo);

        // 按照微信支付的签名规则，拼装StringA
        StringBuffer stringBuffer = new StringBuffer();
        for (String key : paramList) {
            String value = request.getParameter(key);
            if (value==null){
                continue;
            }
            stringBuffer.append(key);
            stringBuffer.append("=");
            stringBuffer.append(value);
            stringBuffer.append("&");
        }
        // 把当前请求的用户的key取出来，拼装 stringSignTemp
        String customerkey = request.getParameter("customerkey");
        String customerSecret = getCustomerSecret(customerkey);
        stringBuffer.append("key");
        stringBuffer.append("=");
        stringBuffer.append(customerSecret);
        String stringSignTemp = stringBuffer.toString();

        String sign = DigestUtil.md5Hex(stringSignTemp).toUpperCase();

        //2. 取出请求中传入的sign，并比较
        String reqeustSign = request.getParameter("sign");

        if (!sign.equals(reqeustSign)){
            log.info("签名错误，计算的签名为={},传入的签名为={}",sign,reqeustSign);
            // 请求就此打住
            currentContext.setSendZuulResponse(false);
            HttpServletResponse response = currentContext.getResponse();
            response.setContentType("text/html;charset=utf-8");
            try {
                response.getWriter().println("签名错误");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return null;
        }

        return null;
    }

    /**
     * 需要从缓存中获取 customerkey 对应的 secret
     * @param customerkey
     * @return
     */
    private String getCustomerSecret(String customerkey) {
        return "sbNCm1JnevqI36LrEaxFwcaT0hkGxFnC";
    }
}
